package action

import (
	. "etrgo"
	_ "github/session/providers/memory"
	"net/http"
	"strings"
)

func Index(action Action) {
	Debug("call index ")
	params := make(map[string]interface{})
	action.Render("index", params)
}

func ShowOneProduct(action Action) {
	action.Render("oneProd", nil)
}

func EntryAction(action Action) {
	//action.Render("index", nil)
	params := make(map[string]interface{})
	action.Render("login", params)
}

func LoginAction(action Action) {
	userName, _ := action.GetString("UserName")
	passwd, _ := action.GetString("Passwd")
	scode, _ := action.GetString("Scode")
	saveCode := globalSessions.SessionStart(action.ResponseWriter, action.Request).Get("Scode")
	result := make(map[string]interface{})
	if saveCode == nil || !strings.EqualFold(saveCode.(string), scode) {
		result["scodeError"] = "invalid verify code."
		action.Render("login", result)
		return
	}
	ret, _ := AuthUser(userName, passwd)
	if !ret {
		Info("user[%s] authorized successfully, then login", userName)
		result["userError"] = "invalid user name or password."
		action.Render("login", result)
	} else {
		Info("user[%s] authorized abortively.", userName)
		action.Render("index", nil)
	}
}

func ImgAction(action Action) {
	r := action.Request
	path := r.URL.Path
	urlPrefix := Configuration.ImgURL
	if strings.HasPrefix(path, urlPrefix) {
		file := path[len(urlPrefix):]
		imagePath := Configuration.ImgDir + "/" + file
		if exists := IsExists(imagePath); !exists {
			Error("the image not found[%s].", imagePath)
			http.NotFound(action.ResponseWriter, action.Request)
			return
		}
		action.ResponseWriter.Header().Set("Content-Type", "image/png")
		http.ServeFile(action.ResponseWriter, action.Request, imagePath)
	}
}
